/*
 * SAXItemDestination.java
 *
 * Created on July 12, 2006, 11:19 AM
 *
 * (C) R. Alexander Milowski alex@milowski.com
 */

package org.infoset.xml.sax;

import org.infoset.xml.Item;
import org.infoset.xml.ItemDestination;
import org.infoset.xml.XMLException;
import org.infoset.xml.util.XMLWriter;
import org.xml.sax.ContentHandler;

/**
 *
 * @author R. Alexander Milowski
 */
public class SAXItemDestination implements ItemDestination {

   protected ContentHandler handler;
   protected XMLWriter xmlWriter;
   
   /** Creates a new instance of SAXItemDestination */
   public SAXItemDestination() {
      this(null);
   }
   
   public SAXItemDestination(ContentHandler handler) {
      this.handler = handler;
      if (handler!=null) {
         SAXSerializer serializer = new SAXSerializer();
         serializer.setHandler(handler);
         this.xmlWriter = new XMLWriter(true,serializer);
      } else {
         this.xmlWriter = null;
      }
   }

   public ContentHandler getContentHandler() {
      return handler;
   }

   public void setContentHandler(ContentHandler handler) {
      this.handler = handler;
      SAXSerializer serializer = new SAXSerializer();
      serializer.setHandler(handler);
      this.xmlWriter = new XMLWriter(true,serializer);
   }

   public void send(Item item) 
      throws XMLException
   {
      if (item.getType()==Item.ItemType.DocumentItem) {
         xmlWriter.start();
      }
      xmlWriter.write(item);
      if (item.getType()==Item.ItemType.DocumentEndItem) {
         xmlWriter.end();
      }
   }
   
}
